﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SocketServer.ServerBase;
using SocketServer;
using IUploading;

namespace SocketServer.ClientCommands
{
    public class PostAll : ClientRequestPackCommand<TransferDataPackge>
    {
        public IUpload Uploader = null;

        public string OutParams = "";

        public ClientRequestPackSession Session;

        public TransferServer Server = null;

        public override void ExecuteCommand(ClientRequestPackSession session, TransferDataPackge pack)
        {
            Session = session;
            Server = session.AppServer as TransferServer;
            Server.OnNewSessionRequestReceived(session, pack);
            List<KeyValuePair<string, string>> listPostFailedInterfaces = null;
            try
            {
                if (Server.PostAll(pack.InParams, out listPostFailedInterfaces))
                {
                    OnPostOK("");
                }
                else
                {
                    StringBuilder buildStr = new StringBuilder();
                    for (int i = 0; i < listPostFailedInterfaces.Count; i++)
                    {
                        string msg = string.Format("{0}:{1};", listPostFailedInterfaces[i].Key, listPostFailedInterfaces[i].Value);
                        buildStr.Append(msg);
                    }
                    OnPostFailed(buildStr.ToString(), "");
                }
            }
            catch (Exception ex)
            {
                Server.OnCatchException(session, Uploader, TransferAction.PostAll, ex);
                return;
            }
        }

        protected void OnPostOK(string outParams)
        {
            TransferResponsePackge pack = new TransferResponsePackge("PostAll", TransferAction.PostAll);
            pack.Success = true;
            pack.Result = TransferResult.PostOK;
            pack.Message = "";
            pack.SetParams(outParams);
            if (Session.Connected)
            {
                Session.Send(pack);
            }
            Server.ReportTransferReponse(pack);
        }

        protected void OnPostFailed(string reason, string outParams)
        {
            TransferResponsePackge pack = new TransferResponsePackge("PostAll", TransferAction.PostAll);
            pack.Success = true;
            pack.Result = TransferResult.PostFailed;
            pack.Message = reason;
            pack.SetParams(outParams);
            if (Session.Connected)
            {
                Session.Send(pack);
            }
            Server.ReportTransferReponse(pack);
        }
    }
}
